package com.bookmanger.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookmanger.common.result.Result;
import com.bookmanger.common.utils.PasswordUtil;
import com.bookmanger.common.utils.UserIdThreadLocal;
import com.bookmanger.entity.Book;
import com.bookmanger.entity.User;
import com.bookmanger.entity.dto.UserInfoDTO;
import com.bookmanger.entity.request.UserInfoRequest;
import com.bookmanger.entity.select.UserListDto;
import com.bookmanger.entity.vo.ListForm;
import com.bookmanger.entity.vo.UserListVo;
import com.bookmanger.mapper.UserMapper;
import com.bookmanger.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author huangfuhao
 * @Date 2024/10/26
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    /**
     * 使用token中得到的用户id查询用户信息
     *
     * @return
     */
    @Override
    public Result<UserInfoDTO> getUserInfo() {
        Long userId = UserIdThreadLocal.getUserId();
        if (userId == null) {
            return Result.unauthorizel("用户未登录");
        }
        User user = this.getById(userId);
        if (user == null){
            return Result.error("用户不存在");
        }
        UserInfoDTO userInfoDTO = BeanUtil.copyProperties(user, UserInfoDTO.class);
        return Result.success(userInfoDTO);
    }

    /**
     * 更新用户信息
     * @return
     */
    @Override
    public Result<String> updateUserInfo(UserInfoRequest userInfoRequest) {
        Long userId = UserIdThreadLocal.getUserId();
        if (userId == null) {
            return Result.unauthorizel("用户未登录");
        }
        User user=new User();
        if (StringUtils.isNotBlank(userInfoRequest.getPassword())){
            user.setPassword(PasswordUtil.encodePassword(userInfoRequest.getPassword()));
        }else {
            user.setPassword(null);
        }
        if (StringUtils.isNotBlank(userInfoRequest.getEmail())){
            user.setEmail(userInfoRequest.getEmail());
        }else {
            user.setEmail(null);
        }
        if (StringUtils.isNotBlank(userInfoRequest.getStuNo())){
            //绑学号检查一个学号只能绑一个人
            User one = lambdaQuery().eq(User::getStuNo, userInfoRequest.getStuNo()).one();
            if (one==null){
                user.setStuNo(userInfoRequest.getStuNo());
            }
            else {
                return Result.error("学号已被绑定其它账号");
            }
        }else {
            user.setStuNo(null);
        }
        user.setId(userId);
        user.setUsername(null);
        if(this.updateById(user)){
            return Result.success("更新成功");
        }
        return Result.success("更新失败");
    }

    @Override
    public Result<ListForm<UserListVo>> getUserList(UserListDto userListDto) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //用户名查询
        if (StringUtils.isNotBlank(userListDto.getUsername())) {
            queryWrapper.eq("username", userListDto.getUsername());
        }
        //状态查询
        if (userListDto.getBanned() != null) {
            queryWrapper.eq("banned", userListDto.getBanned());
        }
        Page<User> userPage = new Page<>(userListDto.getPage(), userListDto.getSize());
        IPage<User> userIPage = page(userPage, queryWrapper);
        List<User> userList = userIPage.getRecords();
        List<UserListVo> userListVoList = userList.stream().map(user -> {
            UserListVo vo = new UserListVo();
            BeanUtil.copyProperties(user, vo);
            vo.setRole("user");
            return vo;
        }).toList();
        ListForm<UserListVo> userListForm = new ListForm<>(userListDto.getPage(),userListDto.getSize(),
                userIPage.getPages(), //总页数
                userIPage.getTotal(), //总记录数
                userListVoList);
        return Result.success(userListForm);
    }

    @Override
    public Result userDisable(Long id) {
        if(baseMapper.selectById(id) == null) {
            return Result.error("id错误");
        }
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("banned", 2);
        boolean result = update(updateWrapper);
        if (result) {
            return Result.success("停用成功");
        } else {
            return Result.error("停用失败");
        }
    }

    @Override
    public Result userEnable(Long id) {
        if(baseMapper.selectById(id) == null) {
            return Result.error("id错误");
        }
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("banned", 0);
        boolean result = update(updateWrapper);
        if (result) {
            return Result.success("解冻成功");
        } else {
            return Result.error("解冻失败");
        }
    }

    @Override
    public Result userFreeze(Long id) {
        if(baseMapper.selectById(id) == null) {
            return Result.error("id错误");
        }
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("banned", 1);
        boolean result = update(updateWrapper);
        if (result) {
            return Result.success("冻结成功");
        } else {
            return Result.error("冻结失败");
        }
    }

    @Override
    public List<User> getUserListByName(String userName) {
        return list(new LambdaQueryWrapper<User>()
                .like(User::getUsername, userName));
    }

    @Override
    public Result<Integer> getUserCount() {
        Long aLong = baseMapper.selectCount(null);
        return Result.success(aLong.intValue());
    }
}
